<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-header-actions">
        <h2>工作流管理</h2>
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          创建工作流
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="工作流名称">
        <el-input
          v-model="searchParams.name"
          placeholder="请输入工作流名称"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="workflowStore.workflows"
      v-loading="workflowStore.loading"
      stripe
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="工作流名称" min-width="200" />
      <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">详情</el-button>
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="primary" @click="handleRun(row)">运行</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="workflowStore.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handlePageChange"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import dayjs from 'dayjs'

const router = useRouter()
const workflowStore = useWorkflowStore()

const searchParams = reactive({
  name: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 20
})

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''
}

const getStatusType = (status) => {
  const typeMap = {
    '运行中': 'primary',
    '已完成': 'success',
    '失败': 'danger',
    '暂停中': 'warning',
    '已暂停': 'info'
  }
  return typeMap[status] || 'info'
}

const fetchList = async () => {
  await workflowStore.fetchWorkflows({
    page: pagination.page,
    page_size: pagination.pageSize,
    name: searchParams.name || undefined
  })
}

const handleSearch = () => {
  pagination.page = 1
  fetchList()
}

const handlePageChange = () => {
  fetchList()
}

const handleCreate = () => {
  router.push('/workflows/new/edit')
}

const handleEdit = (row) => {
  router.push(`/workflows/${row.id}/edit`)
}

const handleView = (row) => {
  router.push(`/workflows/${row.id}`)
}

const handleRun = async (row) => {
  try {
    await ElMessageBox.confirm('确定要运行这个工作流吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await workflowStore.runWorkflow(row.id, {})
    ElMessage.success('工作流已启动')
    fetchList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('运行工作流失败:', error)
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个工作流吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await workflowStore.deleteWorkflow(row.id)
    ElMessage.success('工作流已删除')
    fetchList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除工作流失败:', error)
    }
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style lang="scss" scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
